package test;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

public class ObjectMapper {

    //对象转JSON数据

    public static String objectToJson(Object obj) {
        try {
            StringBuilder json = new StringBuilder("{");
            Class<?> clazz = obj.getClass();
            Field[] fields = clazz.getDeclaredFields();

            for (Field field : fields) {
                field.setAccessible(true);
                Object value = field.get(obj);
                if (value != null) {
                    json.append("\"").append(field.getName()).append("\":\"");
                    json.append(value.toString()).append("\",");
                }
            }

            if (json.length() > 1) {
                json.deleteCharAt(json.length() - 1);
            }
            json.append("}");
            return json.toString();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
            return null;
        }
    }

    //JSON数据转对象

    public static <T> T jsonToObject(String json, Class<T> clazz) {
        try {
            T obj = clazz.getDeclaredConstructor().newInstance();
            Map<String, String> map = parseJsonToMap(json);

            for (Map.Entry<String, String> entry : map.entrySet()) {
                String key = entry.getKey();
                String value = entry.getValue();

                Field field = clazz.getDeclaredField(key);
                field.setAccessible(true);

                if (field.getType() == int.class || field.getType() == Integer.class) {
                    field.set(obj, Integer.parseInt(value));
                } else if (field.getType() == double.class || field.getType() == Double.class) {
                    field.set(obj, Double.parseDouble(value));
                } else if (field.getType() == boolean.class || field.getType() == Boolean.class) {
                    field.set(obj, Boolean.parseBoolean(value));
                } else {
                    field.set(obj, value);
                }
            }
            return obj;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    private static Map<String, String> parseJsonToMap(String json) {
        Map<String, String> map = new HashMap<>();
        json = json.replaceAll("\\s", ""); // 去掉空格
        if (!json.startsWith("{") || !json.endsWith("}")) {
            return map;
        }

        String[] entries = json.substring(1, json.length() - 1).split(",");
        for (String entry : entries) {
            String[] keyValue = entry.split(":");
            if (keyValue.length == 2) {
                String key = keyValue[0].replaceAll("\"", "");
                String value = keyValue[1].replaceAll("\"", "");
                map.put(key, value);
            }
        }
        return map;
    }

    public static void main(String[] args) {
        // 测试对象
        class TestObject {
            private String name;
            private int age;

            public TestObject() {}

            public TestObject(String name, int age) {
                this.name = name;
                this.age = age;
            }

            @Override
            public String toString() {
                return "TestObject{name='" + name + "', age=" + age + "}";
            }
        }

        // 测试对象转JSON
        TestObject obj = new TestObject("Alice", 18);
        String json = objectToJson(obj);
        System.out.println("对象转JSON: " + json);

        // 测试JSON转对象
        TestObject newObj = jsonToObject(json, TestObject.class);
        System.out.println("JSON转对象: " + newObj);
    }
}

